<?php
namespace Admin\Controller;
use Think\Controller;

class ApiController extends Controller {
	public function Index()
	{
		$res = array('rcode'=>1,'data'=>date('Y-m-d H:i:s'),'msg'=>'OK');
		echo json_encode( $res );
		exit();
	}

	public function ifServiceReady()
	{
		$res = array('rcode'=>1,'data'=>date('Y-m-d H:i:s'),'msg'=>'OK');
		$res['version'] = '1.6';//系统版本
		echo json_encode( $res );
		exit();
	}

	/**
	 * 自助服务系统接口代理
	 * 
	*/
	public function agent()
	{
		$action = I('get.api_action', 'trim', '');
		$method = I('get.api_method', 'trim', '');

		$res = array('result'=>'error', 'msg'=>'接口请求错误','code'=>'4001');
		if ($action&&$method){
			$action = strtolower( $action );
			$method = ucfirst($method);
			$service = $action.$method;
			$MService = D('Admin/OrderApi','Service');
			if (method_exists($MService, $service)){
				$res = $MService->$service();
			}
			else{
				$res = $MService->apiError();
			}
		}
		$api = $action.'/'.$method;
		$this->_api_log($api, $res);
		e_json( $res );
	}

	private function _api_log($api, $res)
	{
		$log_dir = LOG_PATH.'/api/'.date('Ym').'/';
		if (!file_exists($log_dir)){
			mkdir($log_dir,0755, true);
		}
		$file_path = $log_dir.date('Y_m_d').'.log';
		ob_start();
		echo str_repeat('**',4),"\t",date('Y-m-d H:i:s'),"\t",str_repeat('**',4),"\n";
		echo "API:",$api,"\n";
		echo 'URL:',$_SERVER['REQUEST_URI'],"\n";
		echo "IP:",getip(),"\n";
		echo "reuest data\n";
		if (IS_GET){
			print_r( $_GET);
		}
		else{
			print_r($_POST);
		}
		echo "\nreponse data\n";
			print_r($res);
		echo str_repeat('**',4),"    end    ",str_repeat('**',4),"\n\n";
		$cnt = ob_get_contents();
		ob_end_clean();	
		try{
            file_put_contents($file_path, $cnt, FILE_APPEND);
        }   catch (Exception $e) {
            Log::write('外部接口调用写入日志失败，错误信息：'.$e->getMessage(),'ERR');
        }
	}
}

?>